<?
session_start();
if ($_SESSION['auth'] != true && ($_SESSION['rule'] != "PROVIDER" || $_SESSION['rule'] != "PUBLISHER")) {
	die('please log in.');
}
include_once("includes/connect.inc.php");

switch($_GET['action']){
case "get_files":
	if(empty($_GET['id'])){
		echo "error: item id not found ";
		exit;
	}
	$files = showFileByItem($_GET['id']);
	echo "<table>";	
	echo "<tr><td><input type='file' onchange='upload()' id='uniqueId' name='uniqueId' /></td>";
	echo "<td><img id='loading' src='img/loading.gif' style='display:none;'></td></tr>";
	if($files != ''){
		foreach($files as $f){
			$currUrl = 'http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '\\');
			$link = $currUrl."/".$f['link'];
			echo "<tr id='file".$f['id']."'>";
			echo "<td>$link</td>";
			echo "<td><a href='#' onclick='remove(".$f['id'].")'>remove</a></td>";
			echo "</tr>";
		}
	}
	echo "</table>";
	break;
	
case "upload":
	if(empty($_GET['id'])){
		echo "error: item id not found ";
		exit;
	}
	$error = "";
	$msg = "";
	$fileElementName = 'uniqueId';
	if(!empty($_FILES[$fileElementName]['error'])){
		switch($_FILES[$fileElementName]['error']){
			case '1':
				$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
				break;
			case '2':
				$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
				break;
			case '3':
				$error = 'The uploaded file was only partially uploaded';
				break;
			case '4':
				$error = 'No file was uploaded.';
				break;
			case '6':
				$error = 'Missing a temporary folder';
				break;
			case '7':
				$error = 'Failed to write file to disk';
				break;
			case '8':
				$error = 'File upload stopped by extension';
				break;
			case '999':
			default:
				$error = 'No error code avaiable';
		}
	}elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
	{
		$error = 'No file was uploaded..';
	}else 
	{
		$allowedFileType = array('image/gif','image/jpeg','image/png','image/x-png','application/pdf'
			,'application/msword','application/vnd.ms-excel','text/plain'); 
		$uploadPath = './upload';
		$limitSize = 1024000;
		$inputname = $fileElementName;
		
		$name = $_FILES[$fileElementName]['name'];
		$extPos = strrpos($name,'.');
		if($extPos > 0)$ext = substr($name,$extPos);
		$fileName = mktime().$ext;
		
		$fileId = uploadFile($_GET['id'],$inputname,$limitSize
			,$allowedFileType,$uploadPath.'/'.$fileName,$_FILES,$error);

		$currUrl = 'http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '\\');
		$link = $currUrl.substr($uploadPath,1).'/'.$fileName;
			
	}	
		
	echo "{";
	echo				"error: '" . $error . "',\n";
	echo				"fileId: '" . $fileId . "',\n";
	echo				"link: '" . $link . "'\n";
	echo "}";
	break;
	
case "unload":
	if(empty($_GET['id'])){
		echo "error: item id not found ";
		exit;
	}
	unloadFile($_GET['id']);
	echo "removed file";
	break;
	
default:
	echo "error somehow. please contract helpdesk.";
	break;
}
?>

<?
//lib
function showFileByItem($itemId){
	global $db;
	$sql = "SELECT id,link,itemid FROM file WHERE itemid = '" . $itemId . "'";
	$query = $db->sql_query($sql);
	return $db->sql_fetchrowset($query);
}

function uploadFile($itemId,$inputname,$maxfilesize,$allowedFileType,$finalLocation,$FILES,&$error){
	if (!is_uploaded_file($FILES[$inputname]['tmp_name'])) {
		$error = "You did not upload a file!";
		unlink($FILES[$inputname]['tmp_name']);
	} else {
		if ($FILES[$inputname]['size'] > $maxfilesize) {
			  $error = "file is too large";
			  unlink($FILES[$inputname]['tmp_name']);
		} else {
			$isAllowedType=false;
			foreach($allowedFileType as $filetype){
				if($FILES[$inputname]['type'] ==$filetype) $isAllowedType=true;
			}
			
			if (!$isAllowedType) {
				$error = "This file type is not allowed" . $FILES[$inputname]['type'];
				
				unlink($FILES[$inputname]['tmp_name']);
			} else {
			   copy($FILES[$inputname]['tmp_name'],$finalLocation);
			   unlink($FILES[$inputname]['tmp_name']);
			   return addFile($itemId,substr($finalLocation,1));
			}
		}
	}

}
function addFile($itemId,$path){
	global $db;
	
	$sql="INSERT INTO file ";
	$add['itemid'] = $itemId;
	$add['link']=$path;
	$col="";
	$val="";
	foreach($add as $key => $value){
		$value=trim($value);
		if($value!=""){
			$col=$col."$key,";
			$val=$val."'$value',";
		}
	}
	
	if($col!=""){
		$col=" (".substr($col,0,strlen($col)-1).") ";
		$val=" VALUE(".substr($val,0,strlen($val)-1).") ";
		$sql=$sql.$col.$val;
		//echo $sql;
		$db->sql_query($sql);
		return mysql_insert_id();
	}
}
function unloadFile($fileId){
	global $db;
	$sql = "SELECT link FROM file WHERE id='$fileId'";
	$query = $db->sql_query($sql);
	$row = $db->sql_fetchrow($query);
	$filePath = '.'.$row['link'];
	if(file_exists($filePath)){
	//echo $filePath;
		unlink($filePath);
	}
	removeFile($fileId);
}

function removeFile($fileId) {
	global $db;
	$sql = "DELETE FROM file WHERE id = '" . $fileId . "'";
	return $db->sql_query($sql);
}
?>